var goodsDetail;//商品信息

$(function(){

	loadDataById();
	changeNum();
	getUserInfo();

	// 加购物车
	$("#addCart").on("click",function (){
		var userName;
		var userInfo =  getUserInfo();
		
		if(userInfo){
			userName = userInfo.loginName;
		}
		
		if(userName == null || userName == ""){
			$("#tipModal").modal("show");
			
			$("#shopCardLink span.text").html(parseInt($("#shopCardLink span.text").html()) + 1);
			
			$("#sureBtn").on("click",function(){
				window.location.href = "login.html";
			});
		}else{
			addCart();
		}
		
	});
	
	// 立即购买
	$("#buyNow").on("click",function(){
		var userName;
		var userInfo =  getUserInfo();
		
		if(userInfo){
			userName = userInfo.loginName;
		}
		
		if(userName == null || userName == ""){
			$("#tipModal").modal("show");
			
			$("#sureBtn").on("click",function(){
				window.location.href = "login.html";
			});
		}else{
			buyNow();
		}
		
	});
	
});

/**
 * 根据ID加载商品信息
 */
function loadDataById(){
	var str = location.href;
	var goodsId = str.split("=");
	$.ajax({
		type:"get",
		url: basePath +"/goods/detail/" + goodsId[1],
		async:true,
		success:function(data){
			if(data){
				goodsDetail = data.obj;
				$("#position").html(data.obj.goodsName);
				$("#caption").html(data.obj.goodsName);
				$("#price").html(data.obj.price);
				$("#topDesc").html(data.obj.characterDesc);
				
				$(".classic span").on("click",function(){
					$(this).addClass("on").siblings().removeClass("on");
				});
				
				var i = 0;
				var $imgDiv = $("#showbox");
				$imgDiv.empty();
				var images = data.obj.images.split(",");
				for(var i in images){
					var $img = $("<img src='"+images[i]+"' width='430' height='430'> ");
					$imgDiv.append($img);
					i++;
				}
				
				if(i == images.length){
					var showproduct = {
						"boxid":"showbox",
						"sumid":"showsum",
						"boxw":400,//宽度,该版本中请把宽高填写成一样
						"boxh":400,//高度,该版本中请把宽高填写成一样
						"sumw":60,//列表每个宽度,该版本中请把宽高填写成一样
						"sumh":60,//列表每个高度,该版本中请把宽高填写成一样
						"sumi":7,//列表间隔
						"sums":5,//列表显示个数
						"sumsel":"sel",
						"sumborder":1,//列表边框，没有边框填写0，边框在css中修改
						"lastid":"showlast",
						"nextid":"shownext"
				   };//参数定义	  
				   $.ljsGlasses.pcGlasses(showproduct);//方法调用，务必在加载完后执行
				   
				   i = 0;
				}
				
				
				// 详情展示
				var spanText = $("#goodsInfo .detailInfo ul li span.text");
				data.obj.upTime = (new Date(data.obj.upTime)).Format("yyyy-MM-dd");
				
				for(var i in spanText){
					for(var j in data.obj){
						if(spanText.eq(i).attr("name") == j){
							spanText.eq(i).html(data.obj[j]);
						}
					}
				}
				
				// 加载评论
				loadComment();
			}
		}
	});
}

/**
 * 加入购物车
 */
function addCart(){
	var goodsData = {};
	goodsData.goodsId = goodsDetail.id;
	goodsData.goodsName = goodsDetail.goodsName;
	var img = goodsDetail.images.split(",");
	goodsData.price = goodsDetail.price + "";
	goodsData.number = parseInt($("#numSpan").html());
	goodsData.pic = img[0];
	
	$.ajax({
		type:"post",
		url:basePath + "/cart/add",
		data:goodsData,
		async:true,
		success:function(data){
			if(data){
				if(data.status == "200"){
					$("#addSuccess").fadeIn();
					setTimeout(function(){
						$("#addSuccess").fadeOut();
					},1500);
				}else{
					
				}
			}
		}
	});

}

/**
 * 立即购买
 */
function buyNow(){
	var params = {};
	params.goodsCode = goodsDetail.id;
	params.quantity = $("#numSpan").html();
	params.price = goodsDetail.price;
	params.total =(params.quantity * params.price);
	
	var dto= JSON.stringify(params);
	
	$.ajax({
		type:"post",
		url:basePath + "/order/imBuy",
		data:params,
		async:true,
		success:function(data){
			if(data){
				if(data.status == "200"){
					sessionStorage.setItem("orderCode",data.obj.orderCode);
					
					window.location.href = "payPage.html";
				}
			}
		}
	});
}

/**
 * 数量增减
 */
function changeNum(){
	var num = 1;
	$("#addSpan").on("click",function(){
		num ++;
		$("#numSpan").html(num);
	});
	
	$("#cutSpan").on("click",function(){
		num --;
		if($("#numSpan").html() == 0){
			$(this).attr("disabled",true);
			num = 0;
			$("#numSpan").html(num);
			
		}
		$("#numSpan").html(num);
	});
}

/**
 * 加载评论
 */
function loadComment(){
	var str = location.href;
	var goodsId = str.split("=");
	var params = {};
	params.condition = {};
	params.condition.goodsId = parseInt(goodsId[1]);
	$.ajax({
		type:"get",
		url:basePath + "/goods/listGoodsAppraises?page=" + JSON.stringify(params),
		async:false,
		success:function(data){
			if(data){
				var commemtUl = $("#comment .commentList ul");
				commemtUl.html("");
				var data = data.obj.records;
				for(var i in data){
					var lastChart = data[i].username.split("");
					
					var $span = $("<span class='score'></span>");
					for(var j = 0;j<data[i].goodsScore;j++){
						var $i = $("<i class='fa fa-star'></i>");
						$span.append($i);
					}
					
					var $li = $("<li class='clearfix'></li>");
					var $div1 = $("<div class='avatar fl-l'><span class='lastChart'>"+lastChart[lastChart.length-1]+"</span><span class='commemtUserName'>"+data[i].username+"</span></div>");
					var $div2 = $("<div class='rightCommemtText fl-l'></div>");
					var $span2 = $("<span class='buyGoodsName'>"+ goodsDetail.goodsName +"</span>");
					var $spanDiv =  $("<div  class='commemtContent'><span>" + data[i].content +
							"</span></div><span class='commemtTime'>"+(new Date(data[i].createTime)).Format("yyyy-MM-dd")+"</span>");
					
					
					$div2.append($span);
					$div2.append($span2);
					$div2.append($spanDiv);
					$li.append($div1);
					$li.append($div2);
					commemtUl.append($li);
				}
			}
		}
	})
}
/**
 * 获取当前用户信息
 */
function getUserInfo(){
	var currentUser;
	$.ajax({
		type:"get",
		url:basePath + "/user/detail",
		async:false,
		success:function(data){
			if(data){
				currentUser = data.obj;
			}
		}
	});
	return currentUser;
}

/**
 * 格式化时间
 */
Date.prototype.Format = function (fmt) { //author: tony  
    var o = {  
        "M+": this.getMonth() + 1, //月份  
        "d+": this.getDate(), //日  
        "h+": this.getHours(), //小时  
        "m+": this.getMinutes(), //分  
        "s+": this.getSeconds(), //秒  
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度  
        "S": this.getMilliseconds() //毫秒  
    };  
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));  
    for (var k in o)  
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));  
    return fmt;  
};









